package com.tianitan.gen.exception;

import com.tianitan.gen.common.ResponseResult;
import com.tianitan.gen.exception.BaseException;
import com.tianitan.gen.constant.ErrorConstant;
import com.tianitan.gen.common.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 系统异常 预期以外异常
     *
     * @param ex Exception
     * @return
     */
    @ExceptionHandler
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseResult<Void> exceptionHandler(Exception ex) {
        log.error("未知异常信息：{}", ex.getMessage());
        return ResponseResult.error("服务器异常");
    }


    /**
     * 捕获系统业务异常
     *
     * @param ex BaseException
     * @return
     */
    @ExceptionHandler
    public ResponseResult<Void> exceptionHandler(BaseException ex) {
        log.error("系统业务异常：{}", ex.getMessage());
        return ResponseResult.error(ex.getMessage());
    }

    /**
     * 捕获请求参数异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler
    public ResponseResult<Void> HttpRequestMethodNotSupportedExceptionHandler(HttpRequestMethodNotSupportedException ex) {
        log.error("异常信息：{}", ex.getMessage());
        return ResponseResult.error("请求方式异常, 应为" + ex.getSupportedHttpMethods() + "请求");
    }

    /**
     * 捕获SQL重复异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler
    public ResponseResult<Void> SQLIntegrityConstraintViolationExceptionHandler(SQLIntegrityConstraintViolationException ex) {
        String exMessage = ex.getMessage();
        if (exMessage.contains("Duplicate entry")) {
            // 主键重复
            String msg = exMessage.split(" ")[2] + ErrorConstant.ACCOUNT_EXISTS;
            return ResponseResult.error(msg);
        }
        return ResponseResult.error(ErrorConstant.UNKNOWN_ERROR);
    }

    // /**
    //  * 捕获参数校验异常
    //  */
    // @ExceptionHandler(value = BindException.class)
    // public ResponseResult<List<String>> validExceptionHandler(BindException e) {
    //     List<ObjectError> allErrors = e.getAllErrors();
    //     List<String> errorMessageList = allErrors.stream()
    //             .map(DefaultMessageSourceResolvable::getDefaultMessage)
    //             .collect(Collectors.toList());
    //     return ResponseResult.error("参数校验失败", errorMessageList);
    // }

}

